package com.oss.service;

import javax.jdo.PersistenceManager;

import org.apache.commons.lang.StringUtils;

import com.oss.PMF;

/**
 * @author xueqiang.mi
 * @since 2010-8-4
 */
public class BaseService {

	/**
	 * 统一的删除接口
	 * 
	 * @param clazz
	 * @param id
	 */
	public void delete(Class<?> clazz, Object id) {
		PersistenceManager pm = PMF.get();
		try {
			Object obj = pm.getObjectById(clazz, id);
			pm.deletePersistent(obj);
		} finally {
			pm.close();
		}
	}

	protected String generateId(String name) {
		return name.toLowerCase().replaceAll("\\s+", "-");
	}

	protected String getSiteFromUrl(String url) {
		if (!StringUtils.startsWithIgnoreCase(url, "http")) {
			url += "http://";
		}
		int tail = StringUtils.indexOf(url, '/', 10);
		String site = StringUtils.substring(url, 0, tail + 1);
		int number = StringUtils.countMatches(site, ".");
		if (number > 0 && number < 3) {
			return site;
		}
		return null;
	}

	protected String getDefaultSiteName(String site) {
		site = site.replaceFirst("www.", "");
		int number = StringUtils.countMatches(site, ".");
		if (number == 1) {
			String name = StringUtils.substringBetween(site, "://", ".");
			return StringUtils.capitalize(name);
		} else if (number == 2) {
			String name = StringUtils.substringBetween(site, ".", ".");
			String topic = StringUtils.substringBetween(site, "://", ".");
			StringBuilder sb = new StringBuilder();
			sb.append(StringUtils.capitalize(name)).append(" ").append(StringUtils.capitalize(topic));
			return sb.toString();
		}
		return site;
	}
}
